﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExpertMIS.Brokers;
using ExpertMIS.Entities;

namespace ExpertMIS.UserControl
{
    public enum BulletinCatalog
    {
        OrganizationBulletin = 1,
        SocailBulletin = 2
    }

    public partial class ucBulletinList : System.Web.UI.UserControl
    {
        private void RefreshBulletins()
        {
            BulletinBroker broker = new BulletinBroker();

            if (BulletinCatalog == BulletinCatalog.OrganizationBulletin)
            {
                repBulletinList.DataSource = broker.GetOrganizationBulletins(10);
                repBulletinList.DataBind();
            }
            else if (BulletinCatalog == BulletinCatalog.SocailBulletin)
            {
                repBulletinList.DataSource = broker.GetSocialBulletins(10);
                repBulletinList.DataBind();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TitleLength = -1;
            RefreshBulletins();
        }

        public string CSS
        {
            set
            {
                pnBulletin.CssClass = value;
            }
        }

        public bool ShowTitle
        {
            get;
            set;
        }

        public int TitleLength
        {
            get;
            set;
        }

        public string LengthVariable
        {
            get;
            set;
        }

        public BulletinCatalog BulletinCatalog
        {
            get;
            set;
        }

        public bool ShowNewIcon
        {
            get;
            set;
        }

        protected string GetBulletinTitle(object bulletin)
        {
            if (bulletin == null || string.IsNullOrEmpty(bulletin.ToString())) return "";

            int len = -1;
            if(!int.TryParse(ExpertMIS.Codes.Utility.GetEnvironmentValue(LengthVariable), out len))
            {
                len = TitleLength;
            }
            if (len <= 0)
            {
                return bulletin.ToString();
            }
            else
            {
                return ExpertMIS.Codes.Utility.CutLongText(bulletin.ToString(), len);
            }
        }

        protected void repBulletinList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgNew = e.Item.FindControl("imgNew") as Image;
            if (ShowNewIcon && imgNew != null)
            {
                BulletinEntity bulletin = e.Item.DataItem as BulletinEntity;
                if (bulletin != null)
                {
                    // 一周内算新公告，显示imgNew
                    TimeSpan span = DateTime.Now - (DateTime)bulletin.UpdateDate;
                    imgNew.Visible = span.Days <= 7;
                }
            }
        }
    }
}